<template>
  <div class="card text-center">
    <div class="card-body">
      <h5 class="card-title">用户信息</h5>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th scope="col">用户</th>
              <th scope="col">客户端设置</th>
              <th scope="col">数据集设置</th>
              <th scope="col">模型状态</th>
              <th scope="col">验证结果</th>
              <th scope="col">追踪</th>
              <th scope="col">追踪结果</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(user, index) in Clientsusers" :key="index">
              <td>{{ user.name }}</td>
              <td>
                <select v-model="user.setting" @change="handleChange(user)" class="form-select">
                  <option v-for="(option, optionIndex) in settingOptions" :key="optionIndex">{{ option }}</option>
                </select>
              </td>
              <td>
                <select v-model="user.dataset" class="form-select">
                  <option v-for="(option, optionIndex) in getSettingData(user.name)" :key="optionIndex">{{ option }}</option>
                </select>
              </td>
              <td>{{ user.status }}</td>
              <td>{{ user.result1 }}</td>
              <td>
                <button class="btn bg-primary-light text-white"  @click="startProcess(user,index)">请求追踪</button>
              </td>
              <td>{{ user.result2 }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

<!-- 按钮 -->
<div class="container"  style="white-space: nowrap; height: 200px;">
  <div class="card mt-4 text-center">
    <div class="card-body">
      <div class="row mt-2 mb-2">
        <div class="col">
<!--          btn-primary-->
          <button class="btn bg-primary-light text-white btn-lg" style="width: 100%; height: 100%" @click="handleButtonClick(1)">开始训练</button>
        </div>

        <div class="col">
          <button class="btn bg-primary-light text-white btn-lg" style="width: 100%; height: 100%" @click="handleButtonClick(2)">上传模型</button>
        </div>
        <div class="col">
          <button class="btn bg-primary-light text-white btn-lg" style="width: 100%; height: 100%" @click="handleButtonClick(3)">接收模型</button>
        </div>
        <div class="col">
          <button class="btn bg-primary-light text-white btn-lg" style="width: 100%; height: 100%" @click="handleButtonClick(4)">验证模型</button>
        </div>
      </div>
    </div>
  </div>
</div>

</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from "axios";
import {HomeeventBus, AggserverInitialEventBus, TraceserverEventBus, ClientInitialEventBus} from '@/views/event-bus';
// import { useToast } from 'vue-toastification';

const initialUsers = [
  {name: 'user1', setting: '默认设置', dataset:'user1_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user2', setting: '默认设置', dataset:'user2_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user3', setting: '默认设置', dataset:'user3_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user4', setting: '默认设置', dataset:'user4_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user5', setting: '默认设置', dataset:'user5_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user6', setting: '默认设置', dataset:'user6_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user7', setting: '默认设置', dataset:'user7_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user8', setting: '默认设置', dataset:'user8_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user9', setting: '默认设置', dataset:'user9_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
  {name: 'user10', setting: '默认设置', dataset:'user10_train_mnist1.npz',status: '未训练', result1: '未验证', result2: ''},
];

const Clientsusers = ref([]);

const settingOptions = ['默认设置', '伪造hash', '伪造签名1', '伪造签名2'];
// const settingData = ['数据集一', '数据集二', '数据集三'];
const settingData = ref({
    user1: ['user1_train_mnist1.npz', 'user1_train_mnist2.npz', 'user1_train_mnist3.npz'],
    user2: ['user2_train_mnist1.npz', 'user2_train_mnist2.npz', 'user2_train_mnist3.npz'],
    user3: ['user3_train_mnist1.npz', 'user3_train_mnist2.npz', 'user3_train_mnist3.npz'],
    user4: ['user4_train_mnist1.npz', 'user4_train_mnist2.npz', 'user4_train_mnist3.npz'],
    user5: ['user5_train_mnist1.npz', 'user5_train_mnist2.npz', 'user5_train_mnist3.npz'],
    user6: ['user6_train_mnist1.npz', 'user6_train_mnist2.npz', 'user6_train_mnist3.npz'],
    user7: ['user7_train_mnist1.npz', 'user7_train_mnist2.npz', 'user7_train_mnist3.npz'],
    user8: ['user8_train_mnist1.npz', 'user8_train_mnist2.npz', 'user8_train_mnist3.npz'],
    user9: ['user9_train_mnist1.npz', 'user9_train_mnist2.npz', 'user9_train_mnist3.npz'],
    user10: ['user10_train_mnist1.npz', 'user10_train_mnist2.npz', 'user10_train_mnist3.npz'],

    // 添加其他用户的 settingData
});

//设置axios
const apiBaseUrl = (window.webConfig && window.webConfig.webApiBaseUrl) || process.env.VUE_APP_BACKEND_API;
const apiClient = axios.create({
  baseURL: apiBaseUrl,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 定义一个方法来根据 user.name 返回相应的 settingData
const getSettingData = (userName) => {
    // 如果有对应的设置数据，返回该用户的 settingData，否则返回一个空数组
    return settingData.value[userName] || [];
};
// 监听来自初始化按钮的事件，执行初始化操作
AggserverInitialEventBus.value.addEventListener('initializeClients', () => {
  // 重置 clients 为初始数据
  Clientsusers.value = [...initialUsers];

  // 将初始数据保存到本地存储
  // localStorage.setItem('users', JSON.stringify(users.value));
  saveUsersToLocalStorage();
  loadUsersFromLocalStorage();
});


// 从本地存储中获取用户设置
const loadUsersFromLocalStorage = () => {
  const storedUsers = JSON.parse(localStorage.getItem('Clients_users'));
  if (storedUsers) {
    Clientsusers.value = storedUsers;
  } else {
    Clientsusers.value = [...initialUsers];
  }
};

// 将用户设置保存到本地存储
const saveUsersToLocalStorage = () => {
  localStorage.setItem('Clients_users', JSON.stringify(Clientsusers.value));
};

// 组件挂载时加载用户设置
onMounted(() => {
  loadUsersFromLocalStorage();
});

// 组件卸载时保存用户设置到本地存储
onUnmounted(() => {
  saveUsersToLocalStorage();
});

// 设置值转换函数
const convertSettingToNumber  = (setting) => {
  switch (setting) {
    case '默认设置':
      return 0;
    case '伪造hash':
      return 1;
    case '伪造签名1':
      return 2;
    case '伪造签名2':
      return 3;
    default:
      return -1; // 或其他合适的默认值
  }
};
// const convertDatasetToNumber  = (dataset) => {
//   switch (dataset) {
//     case '数据集一':
//       return 1;
//     case '数据集二':
//       return 2;
//     case '数据集三':
//       return 3;
//     default:
//       return -1; // 或其他合适的默认值
//   }
// };

const handleChange = (user) => {
  console.log('Before change - user.setting:', user.setting); // 添加调试代码

  if (user.setting === '默认设置') {
    // 如果设置为默认设置，不执行任何操作
    return;
  }

  // 统计当前设置为默认设置的用户数量
  const defaultSettingsCount = Clientsusers.value.filter(u => u.setting === '默认设置').length;

  // 如果当前设置为默认设置的用户数量不超过总用户数量的一半，则禁止设置其他设置
  if (defaultSettingsCount <= Clientsusers.value.length / 2) {
    // 将设置重置为默认设置
    user.setting = '默认设置';
    // 弹窗提示
    alert('当前设置为默认设置的用户数量不足一半，无法进行其他设置！');
  }
// 保存用户设置到本地存储
  saveUsersToLocalStorage();
  console.log('After change - user.setting:', user.setting); // 添加调试代码
};

//限制按钮在未响应前点击
const isProcessing = ref(false);
const startProcess = async (user,index) => {
  if (isProcessing.value) {
    alert('请求正在处理中...');
    return;
  }
  isProcessing.value = true;
  user.result2 = '处理中...';
  console.log('index', index);
  try {
    // const response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client.vue`, {
    const response = await apiClient.post(`/Client`, {
      task:"trace_request",
      idx: index
    });

    if (response.status === 200) {
      // 触发更新事件并传递更新的 idx 数据
      const idx = response.data.request_id
      TraceserverEventBus.value.dispatchEvent(new CustomEvent('trace_request', { detail: idx }));
      console.log('按钮',index,'的响应:', response.data);
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isProcessing.value = false;
  }
};
//限制按钮在未响应前点击
let isButtonClicked = false;
const handleButtonClick = async (buttonNumber) => {
  try {
    // 检查按钮是否已经被点击，如果是，则直接返回
    if (isButtonClicked) {
      alert('正在等待上一次请求的响应，请稍后...');
      console.log('按钮已经被点击，正在等待上一次请求的响应...');
      return;
    }
    // 按钮被点击，设置状态为 true
    isButtonClicked = true;
    let response;
    // const notDefaultSettingsIndices = [];
    let settings = [];
    let datasets = [];
    switch (buttonNumber) {
      case 1:
        //初始化前端页面
        alert('客户端模型已开始训练，请耐心等待...');
        Clientsusers.value.forEach(user => {user.status = '未训练';user.result1 = '未验证';user.result2=''});
        saveUsersToLocalStorage();
        ClientInitialEventBus.value.dispatchEvent(new CustomEvent('initializePages'));
        try {
          // 统计所有用户的setting值，并向后端发送请求
          settings = Clientsusers.value.map(user => convertSettingToNumber(user.setting));
          datasets = Clientsusers.value.map(user => (user.dataset));
          // response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client.vue`, {task:"local_train", local_settings: settings,local_datasets:datasets });
          response = await apiClient.post(`/Client`, {task:"local_train", local_settings: settings,local_datasets:datasets });
          if (response.status === 200) {
            alert('客户端模型训练完成，继续下一步操作...');
           // 获取 users 中的 setting 数据
            const updatedSettings = Clientsusers.value.map(user => user.setting);
            console.log('updatedSettings:', updatedSettings);
            // 触发更新事件并传递更新的 setting 数据
            HomeeventBus.value.dispatchEvent(new CustomEvent('updateClients', { detail: updatedSettings }));
            // 点击按钮1后，将所有用户的状态设置为B
            Clientsusers.value.forEach(user => {user.status = '待上传';});
            saveUsersToLocalStorage();
            }
          console.log('提交成功:', settings);
          console.log('提交成功:', response.data);
          console.log('Settings sent successfully:', response.data);
        } catch (error) {
          console.error('Error sending settings:', error);
        }
        break;

      case 2:
        try {
          // response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client.vue`,{task:"post_model"});
          response = await apiClient.post(`/Client`,{task:"post_model"});

          if (response.status === 200) {
           // 点击按钮2后，将所有用户的状态设置为C
            Clientsusers.value.forEach(user => {user.status = '已上传';});
            saveUsersToLocalStorage();
            console.log('按钮2的响应:', response.data);
          } else{
            console.error('响应失败');
          }
        } catch (error) {

          console.error('请求失败:', error);
        }
        break;
      case 3:
        try {
          // response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client.vue`,{task:"client_receive_model"});
          response = await apiClient.post(`/Client`,{task:"client_receive_model"});
          if (response.status === 200) {
           // 点击按钮3后，将所有用户的状态设置为D
            Clientsusers.value.forEach(user => {user.status = '已接收';});
            saveUsersToLocalStorage();
            console.log('按钮3的响应:', response.data);
          } else{
            console.error('响应失败');
          }
        } catch (error) {
          console.error('请求失败:', error);
        }
        break;
      case 4:
        try {
          alert('客户端已开始验证模型，请耐心等待...');
          // response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client.vue`,{task:"client_verify"});
          response = await apiClient.post(`/Client`,{task:"client_verify"});
          if (response.status === 200) {
            alert('验证结束，继续下一步操作...');
            const updatedArray = response.data;
            // 根据返回的数组更新 users 中的 result1
            Clientsusers.value = Clientsusers.value.map((user, index) => ({
              ...user,
              result1: updatedArray[index] ? '验证成功' : '验证失败'
            }));
            console.log('按钮4的响应:', response.data);
          } else{
            console.error('响应失败');
          }
        } catch (error) {
          console.error('请求失败:', error);
        }
        break;
      default:
        console.error('未知的按钮编号:', buttonNumber);
        break;
    }
    // 请求完成后，设置状态为 false，允许下一次点击
    isButtonClicked = false;
  } catch (error) {
    console.error('请求失败:', error);
    // 请求完成后，设置状态为 false，允许下一次点击
    isButtonClicked = false;
  }
};

</script>


// 在此之后，你可以根据需要修改 serverState 的值，以更新背景颜色和文本
<style scoped>
.bg-primary-light {
  background-color: #152ca8 !important; /* 淡蓝色 */
}

.bg-danger-light {
  background-color: #a12004 !important; /* 淡灰色 */
}
.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}
.disabled1 {
  pointer-events: none;
  opacity: 1;
}
</style>
